{% extends 'base.html' %}
{% block title %}Pods{% endblock %}
{% block nav-item-2 %}layui-nav-itemed{% endblock %}
{% block nav-child-2-4 %}layui-this{% endblock %}
{% block content %}
   {% csrf_token %}
<span class="layui-breadcrumb">
  <a href="#">首页</a>
  <a href="#">Kubernetes</a>
  <a><cite>Pods</cite></a>
</span>
<hr class="layui-border-red">
<div class="layui-card">
    <div class="layui-card-body">
        <div class="layui-row layui-col-space10">
            <div class="layui-col-md12">
{#                <button class="layui-btn" style="float: left">创建</button>#}
                <input type="text" name="name" class="layui-input" style="width: 150px;float: left" placeholder="输入名称" >
                <button class="layui-btn" style="float: left" id="searchBtn">搜索</button>
            </div>

            <div class="layui-col-md12">
                <table id="test" lay-filter="test"></table>
                <script type="text/html" id="barDemo">
                  <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="yaml">YAML</a>
                  <a class="layui-btn layui-btn-xs" lay-event="log">日志</a>
                    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="terminal" style="color: #FFF;background-color: #385985">终端</a>
                  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">重建</a>
                </script>
            </div>
        </div>
    </div>
</div>
<div  id="log"  style="display: none">
   <div id="log-text" style="background-color: black;color: white;padding: 10px;font-size: 16px">
   </div>
</div>
{% endblock %}
{% block js %}
<script>

// 获取当前命名空间
var storage = window.sessionStorage;
var namespace = storage.getItem('namespace');

layui.use('table', function(){
  var table = layui.table;
  var $ = layui.jquery;
  //动态渲染表格
  table.render({
    elem: '#test'
    ,url: '{% url 'pod_api' %}?namespace=' + namespace //数据接口
    ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
    ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
      title: '提示'
      ,layEvent: 'LAYTABLE_TIPS'
      ,icon: 'layui-icon-tips'
    }]
    ,page: true //开启分页
    ,cols: [[ //表头
        {field: 'name', title: '名称', sort: true}
        ,{field: 'namespace', title: '命名空间',sort: true}
        ,{field: 'pod_ip', title: 'IP地址'}
        ,{field: 'labels', title: '标签', templet: labelsFormat}
        ,{field: 'containers', title: '容器组', templet: containersFormat}
        ,{field: 'status', title: '状态',sort: true, templet: statusFormat}
        ,{field: 'create_time', title: '创建时间'}
      ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:250}
    ]]
      ,id: "TT"
  });
    // 标签格式化
    function labelsFormat(d) {
        result = "";
        if (d.labels == null) {
            return "None"
        } else {
            for(let key in d.labels) {
                result += '<span style="border: 1px solid #009688;border-radius: 5px">' + key + ':' + d.labels[key] + '</span><br>'
            }
            return result
        }
    }
    function containersFormat(d) {
        result = "";
        if (d.containers) {
            for (let key in d.containers) {
                data = d.containers[key];
                result += key + ':' + data.c_name + '=' + data.c_image + '<br>' +
                    '重启次数:' + data.restart_count + '<br>' +
                    '状态:' + data.c_status + '<br>'
            }
            return result
        } else {
            return "None"
        }
    };
    function statusFormat(d) {
        result = "";
        if(d.status == "None"){
            for(let key in d.containers) {
                result += d.containers[key].c_status + '<br>'
            }
            return result
        } else {
            return d.status
        }
    }
  //监听行工具事件
  table.on('tool(test)', function(obj){
    var data = obj.data;
    //console.log(obj)
    if(obj.event === 'del'){
      layer.confirm('你要真要重建' + data.name + ' Pod吗？', function(index){
        var csrf_token = $('[name="csrfmiddlewaretoken"]').val();
        $.ajax({
            type: "DELETE",
            url: "{% url 'pod_api' %}",
            data: data,
            headers: {'X-CSRFToken': csrf_token},
            success: function (res) {
                if(res.code == 0){
                    obj.del();  // 删除当前页面数据
                    layer.msg(res.msg,{icon: 6, time: 3000}) // 默认停顿3秒
                } else {
                    layer.msg(res.msg,{icon: 5})
                }
            },
            error: function () {
                layer.open({
                    type: 0,
                    title: ['异常信息'],
                    content: "服务器接口异常！"
                })
            }
         });
        layer.close(index);
      });
    } else if(obj.event === 'yaml'){
        layer.open({
            title: "YAML",
            type: 2, // 从一个网址加载
            area: ["50%", "60%"],
            content: '{% url 'ace_editor' %}?resource=pod&' + 'namespace=' + data.namespace + '&name=' + data.name
        })
    } else if(obj.event === 'log'){
        // 逗号拼接容器名，例如 containers=c1, c2
        cs = data['containers'];
        containers = "";
        for (let c in cs) {
            if (c < cs.length-1) {
                containers += cs[c]['c_name'] + ","
            } else {
                containers += cs[c]['c_name']
            }
        }
        layer.open({
            title: "容器日志",
            type: 2,
            area: [ '70%', '80%' ],
            content: '{% url 'pod_log' %}?namespace=' + data.namespace + '&pod_name=' + data.name + '&containers=' + containers
        });
    } else if(obj.event === 'terminal'){
        // 逗号拼接容器名, 例如containers=c1,c2
        cs = data['containers'];
        containers = "";
        for(let c in cs) {
            if (c < cs.length-1) {
                containers += cs[c]['c_name'] + ","
            } else {
                containers += cs[c]['c_name']
            }
        }
        layer.open({
            title: "容器终端",
            type: 2,
            area : [ '70%', '80%' ],
            content: '{% url 'terminal' %}?namespace=' + data.namespace + '&pod_name=' + data.name + '&containers=' + containers
        });
    }
  });
    // 监控搜索事件
    $('#searchBtn').click(function(){
        var search_key = $('input[name="name"]').val();
        table.reload('TT', {
          where: {
              search_key: search_key
          }
        });
    })

});
</script>
{% endblock %}
